document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const loginButton = document.getElementById('loginButton');
    const togglePassword = document.getElementById('togglePassword');
    const errorMessages = document.querySelectorAll('.error-message');
    const loadingSpinner = loginButton.querySelector('.fa-spinner');

    // 显示/隐藏密码
    togglePassword.addEventListener('click', function() {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);

        // 切换图标
        const icon = togglePassword.querySelector('i');
        if (type === 'text') {
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });

    // 表单验证
    function validateForm() {
        let isValid = true;

        // 清除所有错误消息
        errorMessages.forEach(msg => msg.classList.add('hidden'));

        // 验证用户名
        if (!usernameInput.value.trim()) {
            usernameInput.nextElementSibling.nextElementSibling.classList.remove('hidden');
            isValid = false;
        }

        // 验证密码
        if (!passwordInput.value.trim()) {
            passwordInput.nextElementSibling.nextElementSibling.classList.remove('hidden');
            isValid = false;
        }

        return isValid;
    }

    // 登录处理
    loginButton.addEventListener('click', async function() {
        if (!validateForm()) return;

        // 显示加载状态
        loginButton.disabled = true;
        loadingSpinner.classList.remove('hidden');
        loginButton.querySelector('span').textContent = '登录中...';

        try {
            // 收集表单数据
            const formData = {
                username: usernameInput.value,
                password: passwordInput.value
            };

            // 发送登录请求（根据实际情况修改URL）
            const response = await fetch('/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData),
                credentials: 'include' // 允许携带cookie
            });

            // 处理响应
            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) { // 假设成功状态码为200
                    // 成功提示
                    await Swal.fire({
                        icon: 'success',
                        title: '登录成功！',
                        text: '即将跳转到首页',
                        timer: 1500,
                        timerProgressBar: true,
                        showConfirmButton: false,
                        background: '#f5f7fa',
                        iconColor: '#165DFF',
                        color: '#303133',
                        toast: true,
                        position: 'top-end',
                        showClass: {
                            popup: 'animate__animated animate__fadeInUp'
                        },
                        hideClass: {
                            popup: 'animate__animated animate__fadeOutDown'
                        }
                    });
                    window.location.href = '/view/quesList.html';
                } else {
                    // 失败提示
                    Swal.fire({
                        icon: 'error',
                        title: '登录失败',
                        text: result.data || '请检查账号密码',
                        background: '#fef4f4',
                        iconColor: '#FF4444',
                        color: '#606266',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    });
                }
            } else {
                // 服务器错误
                Swal.fire({
                    icon: 'warning',
                    title: '服务器错误',
                    text: '请稍后再试',
                    background: '#fff8d7',
                    iconColor: '#FFB800',
                    color: '#606266',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });
            }
        } catch (error) {
            // 网络错误
            Swal.fire({
                icon: 'info',
                title: '网络连接失败',
                text: '请检查网络设置',
                background: '#e8f4ff',
                iconColor: '#165DFF',
                color: '#303133',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 2000
            });
        } finally {
            // 重置按钮状态
            loginButton.disabled = false;
            loadingSpinner.classList.add('hidden');
            loginButton.querySelector('span').textContent = '登录';
        }
    });

    // 回车键触发登录
    loginForm.addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            loginButton.click();
        }
    });
});